#include "overview_view.h"
#include "ui_overview_view.h"
#include "alarm_rule.h"
#include "database_manager.h"

OverviewView::OverviewView(QWidget *parent)
    : QWidget(parent),
      ui_(new Ui::OverviewView),
      state_info_(new StateInfo()),
      dealer_handler_(DealerHandler::getInstance()),
      control_instruct_num_(0),
      alarm_num_(0)
{
    ui_->setupUi(this);

    // 管理布局
    QGridLayout *layBody = new QGridLayout(this);
    QGridLayout *layBodyL = new QGridLayout;
    QGridLayout *layBodyR = new QGridLayout;

    QGridLayout *layBodyRB = new QGridLayout;
    layBodyL->addWidget(ui_->data_overview_frame, 0, 0);
    layBodyL->addWidget(ui_->traffic_ranking_frame, 1, 0);
    layBodyL->addWidget(ui_->control_instruction_frame, 2, 0);
    layBodyL->setRowStretch(0, 1);
    layBodyL->setRowStretch(1, 1);
    layBodyL->setRowStretch(2, 1);

    layBodyRB->setSpacing(2);
    layBodyRB->setColumnStretch(0, 1);
    layBodyRB->setColumnStretch(1, 1);
    layBodyRB->addWidget(ui_->traffic_alarm_frame);
    layBodyRB->addWidget(ui_->alarm_list_frame);

    layBodyR->setSpacing(2);
    layBodyR->setRowStretch(0, 2);
    layBodyR->setRowStretch(1, 1);
    layBodyR->addWidget(ui_->real_instruction_list_frame, 0, 0);
    layBodyR->addLayout(layBodyRB, 1, 0);

    layBody->setSpacing(2);
    layBody->addLayout(layBodyL, 0, 0, Qt::AlignCenter);
    layBody->addLayout(layBodyR, 0, 1, Qt::AlignCenter);
    layBody->setColumnStretch(0, 1);
    layBody->setColumnStretch(1, 2);
    setLayout(layBody);

    // 定时器
    index_timer_ = new QTimer;
    index_timer_->setInterval(1000 * 300); // 5分钟
    index_timer_->start();
    connect(index_timer_, &QTimer::timeout, this, &OverviewView::on_timeout);

    // 网络应答信号槽
    connect(dealer_handler_, &DealerHandler::messageReceived, this, &OverviewView::onNetworkMessageReceived);
    // 初始化
    initDataOverview();
    initControlInstructionCycle();
    initControlInstruction();
    initTrafficAlarm();
    initAlarmList();
    initRealInstructionList();
}

OverviewView::~OverviewView()
{
    if (index_timer_)
    {
        index_timer_->stop();
        delete index_timer_;
    }
    if (state_info_)
    {
        delete state_info_;
    }
    for (auto sub_state_info : state_info_vec_)
    {
        delete sub_state_info;
    }
    state_info_vec_.clear();
    if (chart_view_top5_)
    {
        delete chart_view_top5_;
    }
    if (chart_view_ctrl_)
    {
        delete chart_view_ctrl_;
    }
    if (chart_view_warn_)
    {
        delete chart_view_warn_;
    }
    delete ui_;
}

void OverviewView::initDataOverview()
{
    // 请求所有子站
    dealer_handler_->sendRequest("select-all-substation", "");
    dealer_handler_->sendRequest("control-instruction-number", "");
    dealer_handler_->sendRequest("alarm-number", "");
    ui_->facNum->setText(QString::number(state_info_vec_.size()));
    ui_->ctrlNum->setText(QString::number(control_instruct_num_));
    ui_->warnNum->setText(QString::number(alarm_num_));
}

void OverviewView::updateDataOverview()
{
    dealer_handler_->sendRequest("select-all-substation", "");
    dealer_handler_->sendRequest("control-instruction-number", "");
    dealer_handler_->sendRequest("alarm-number", "");
}

void OverviewView::initControlInstructionCycle()
{
    QBarSet *ctrl_set = new QBarSet(QString::fromLocal8Bit("控制指令"));
    *ctrl_set << 0 << 0 << 0 << 0 << 0;

    QBarSet *set_set = new QBarSet(QString::fromLocal8Bit("设值指令"));
    *set_set << 0 << 0 << 0 << 0 << 0;
    QBarSeries *series = new QBarSeries();
    series->append(ctrl_set);
    series->append(set_set);

    QChart *chart = new QChart;
    chart->addSeries(series);
    chart->legend()->setLabelColor(Qt::white);
    chart->setMargins(QMargins(0, 0, 0, 0));

    chart->setAnimationOptions(QChart::SeriesAnimations);

    QStringList categories;
    // 根据当前时间获取最新5个月
    QDate currentDate = QDate::currentDate();
    for (int i = 0; i < 5; i++)
    {
        QDate date = currentDate.addMonths(-i);
        categories << date.toString("yyyy-MM");
    }
    QBarCategoryAxis *axisX = new QBarCategoryAxis();
    axisX->append(categories);
    axisX->setGridLineVisible(false);
    chart->addAxis(axisX, Qt::AlignBottom);
    axisX->setLabelsColor(Qt::white);
    QFont font = axisX->labelsFont();
    font.setPointSize(8);
    axisX->setLabelsFont(font);
    axisX->setLabelsAngle(0);
    series->attachAxis(axisX);

    QValueAxis *axisY = new QValueAxis();
    axisY->setRange(0, 25);
    axisY->setGridLineVisible(false);
    chart->addAxis(axisY, Qt::AlignLeft);
    series->attachAxis(axisY);
    axisY->setLabelsColor(Qt::white);

    chart->setBackgroundBrush(QBrush(Qt::transparent));

    chart_view_top5_ = new QChartView(chart);
    chart_view_top5_->setRenderHint(QPainter::Antialiasing);

    QLayout *layout = ui_->traffic_ranking_frame->layout();

    if (layout == nullptr)
    {
        layout = new QGridLayout(ui_->traffic_ranking_frame);
    }
    ui_->traffic_ranking_frame->setLayout(layout);
    layout->addWidget(chart_view_top5_);
    layout->setAlignment(Qt::AlignCenter);

    // 发送网络请求
    dealer_handler_->sendRequest("select-control-instruction-cycle", "5");
}

void OverviewView::updateControlInstructionCycle()
{
    // 发送网络请求
    dealer_handler_->sendRequest("select-control-instruction-cycle", "5");
}

void OverviewView::refreshControlInstructionCycle()
{
    // 刷新流量排行
    auto series = chart_view_top5_->chart()->series();
    auto axis1 = chart_view_top5_->chart()->axes(Qt::Vertical);
    auto axis2 = chart_view_top5_->chart()->axes(Qt::Horizontal);

    QValueAxis *axisY = (QValueAxis *)axis1[0];
    QBarCategoryAxis *axisX = (QBarCategoryAxis *)axis2[0];

    axisX->setCategories(categories_);
    axis1 = series[0]->attachedAxes();
    axisX = (QBarCategoryAxis *)axis1[0];
    axisY = (QValueAxis *)axis1[1];

    axisX->setCategories(categories_);

    auto setL = ((QBarSeries *)series[0])->barSets();
    QBarSet *set0 = setL[0];
    QBarSet *set1 = setL[1];

    // 计算最大值
    double maxValue = 0;
    int count = 0;
    for (auto fac : categories_)
    {
        if (count == 5)
            break;
        double ctrlValue = ctrl_list_[0][count];
        double setValue = set_list_[0][count];
        set0->replace(count, ctrlValue);
        set1->replace(count, setValue);

        // 更新最大值
        maxValue = std::max(maxValue, std::max(ctrlValue, setValue));
        count++;
    }

    // 设置Y轴范围，留出一些空间
    double range = maxValue * 1.2; // 增加20%的空间
    axisY->setRange(0, range);
}

void OverviewView::initControlInstruction()
{
    QLineSeries *seri = new QLineSeries;

    QChart *chart = new QChart();
    chart->addSeries(seri);

    // 创建分类轴
    QValueAxis *axisX = new QValueAxis();
    axisX->setGridLineVisible(false);
    axisX->setLabelsColor(Qt::white);
    QFont font = axisX->labelsFont();
    font.setPointSize(8);
    axisX->setLabelsFont(font);
    axisX->setLabelsAngle(40);
    chart->addAxis(axisX, Qt::AlignBottom);
    seri->attachAxis(axisX);

    QValueAxis *axisY = new QValueAxis();
    axisY->setRange(0, 10);
    axisY->setGridLineVisible(false);
    chart->addAxis(axisY, Qt::AlignLeft);
    seri->attachAxis(axisY);
    axisY->setLabelsColor(Qt::white);
    chart->setBackgroundBrush(QBrush(Qt::transparent));

    chart_view_ctrl_ = new QChartView(chart);
    chart_view_ctrl_->setRenderHint(QPainter::Antialiasing);

    chart_view_ctrl_->setStyleSheet("background-color: transparent; color: white;");
    chart_view_ctrl_->setChart(chart);
    QLayout *layout = ui_->control_instruction_frame->layout();

    if (layout == nullptr)
    {
        layout = new QVBoxLayout(ui_->control_instruction_frame);
    }
    ui_->control_instruction_frame->setLayout(layout);
    layout->addWidget(chart_view_ctrl_);
    layout->setAlignment(Qt::AlignCenter);

    // 发送网络请求
    dealer_handler_->sendRequest("last-30days-instruction-count", "");
}

void OverviewView::updateControlInstruction()
{
    dealer_handler_->sendRequest("last-30days-instruction-count", "");
}

void OverviewView::refreshControlInstruction()
{
    // 刷新流量趋势
    auto seris = chart_view_ctrl_->chart()->series();
    QLineSeries *cur_seri = (QLineSeries *)seris[0];
    cur_seri->clear();

    int max = 0;
    // 显示所有数据点
    for (int i = 0; i < control_instruction_vec_.size(); i++)
    {
        cur_seri->append(i, control_instruction_vec_[i]);
        if (max < control_instruction_vec_[i])
        {
            max = control_instruction_vec_[i];
        }
    }

    
    // 更新X轴
    QValueAxis *axisX = (QValueAxis *)chart_view_ctrl_->chart()->axisX();
    axisX->setRange(0, control_instruction_vec_.size());
    axisX->setTickInterval(7);
    axisX->setLabelFormat("%dd");
    chart_view_ctrl_->chart()->axisY()->setRange(0, max * 1.2);
}

void OverviewView::initTrafficAlarm()
{
    QLineSeries *seri = new QLineSeries;
    seri->append(0, 2);
    seri->append(1, 4);
    seri->append(2, 5);
    seri->append(3, 6);
    seri->append(4, 9);
    seri->append(5, 6);
    seri->append(6, 7);

    QChart *chart = new QChart();
    chart->addSeries(seri);

    QValueAxis *axisX = new QValueAxis();
    axisX->setRange(0, 6);
    axisX->setTickInterval(1);
    axisX->setGridLineVisible(false);
    chart->addAxis(axisX, Qt::AlignBottom);
    axisX->setLabelsColor(Qt::white);
    QFont font = axisX->labelsFont();
    font.setPointSize(8);
    axisX->setLabelsFont(font);
    axisX->setLabelsAngle(45);
    seri->attachAxis(axisX);

    QValueAxis *axisY = new QValueAxis();
    axisY->setRange(0, 10);
    axisY->setGridLineVisible(false);
    chart->addAxis(axisY, Qt::AlignLeft);
    seri->attachAxis(axisY);
    axisY->setLabelsColor(Qt::white);
    chart->setBackgroundBrush(QBrush(Qt::transparent));

    chart_view_warn_ = new QChartView(chart);
    chart_view_warn_->setRenderHint(QPainter::Antialiasing);

    chart_view_warn_->setStyleSheet("background-color: transparent; color: white;");
    chart_view_warn_->setChart(chart);
    QLayout *layout = ui_->traffic_alarm_frame->layout();

    if (layout == nullptr)
    {
        layout = new QVBoxLayout(ui_->traffic_alarm_frame);
    }
    ui_->traffic_alarm_frame->setLayout(layout);
    layout->addWidget(chart_view_warn_);
    layout->setAlignment(Qt::AlignCenter);
    dealer_handler_->sendRequest("last-30days-alarm-count", "");
}

void OverviewView::updateTrafficAlarm()
{
    dealer_handler_->sendRequest("last-30days-alarm-count", "");
}

void OverviewView::refreshTrafficAlarm()
{
    // 刷新告警趋势
    auto seris = chart_view_warn_->chart()->series();

    QLineSeries *cur_seri = (QLineSeries *)seris[0];

    cur_seri->clear();

    int count = 1;
    int max = 0;
    for (auto elem : last_30days_alarm_count_)
    {
        cur_seri->append(count - 1, elem);
        if (max < elem)
        {
            max = elem;
        }
        count++;
    }

    QValueAxis *axisX = (QValueAxis *)chart_view_warn_->chart()->axisX();
    axisX->setRange(0, count - 1);
    axisX->setTickInterval(7);
    axisX->setLabelFormat("%dd");
    chart_view_warn_->chart()->axisY()->setRange(0, max * 1.2);
}

void OverviewView::initAlarmList()
{
    ui_->tableWarn->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); // 某列适应内容
    ui_->tableWarn->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); // 某列适应内容
    ui_->tableWarn->horizontalHeader()->setStretchLastSection(true);
    dealer_handler_->sendRequest("get-alarm-record", "20");
}

void OverviewView::updateAlarmList()
{
    dealer_handler_->sendRequest("get-alarm-record", "20");
}

void OverviewView::refreshAlarmList()
{
    // 清空表格
    ui_->tableWarn->setRowCount(0);

    for (auto alarm_record : alarm_record_vec_)
    {
        int row = ui_->tableWarn->rowCount();
        ui_->tableWarn->insertRow(row);

        // 告警产生时间
        qint64 createdAt = alarm_record->create_at();
        QDateTime createTime = QDateTime::fromMSecsSinceEpoch(createdAt);
        QTableWidgetItem *createItem = new QTableWidgetItem(createTime.toString("yyyy-MM-dd hh:mm:ss"));
        ui_->tableWarn->setItem(row, 0, createItem);

        // 子站描述
        QString description = alarm_record->state_info()->description();
        QTableWidgetItem *descItem = new QTableWidgetItem(description);
        ui_->tableWarn->setItem(row, 1, descItem);


        // 告警规则
        AlarmRule *alarm_rule = alarm_record->alarm_rule();
        int metricType = static_cast<int>(alarm_rule->metricType());
        int intervalSeconds = alarm_rule->intervalSecs();

        QString ruleText;
        switch (metricType)
        {
        case MetricTypeEnum::CONTROL_FRAME_TOTAL:
            ruleText = QString("%1秒内控制帧总数越限").arg(intervalSeconds);
            break;
        case MetricTypeEnum::CONTROL_POINT_TOTAL:
            ruleText = QString("%1秒内控制点总数越限").arg(intervalSeconds);
            break;
        case MetricTypeEnum::SAME_YK_POINT:
        {
            QVector<PointInfo> point_list = DatabaseManager::queryPoints(alarm_record->substation_id(), static_cast<int>(PointInfo::Type::YK));
            QString yk_point_desc = "";
            for (const PointInfo &point : point_list)
            {
                if (point.point_id == alarm_record->point_address())
                {
                    yk_point_desc = point.point_desc;
                }
            }
            ruleText = QString("%1秒内多次遥控相同地址%2越限").arg(intervalSeconds).arg(yk_point_desc);
        }
        break;
        case MetricTypeEnum::SAME_SD_POINT:
        {
            QVector<PointInfo> point_list = DatabaseManager::queryPoints(alarm_record->substation_id(), static_cast<int>(PointInfo::Type::YT));
            QString sd_point_desc = "";
            for (const PointInfo &point : point_list)
            {
                if (point.point_id == alarm_record->point_address())
                {
                    sd_point_desc = point.point_desc;
                }
            }
            ruleText = QString("%1秒内多次设值相同地址%2越限").arg(intervalSeconds).arg(sd_point_desc);
        }
        break;
        case MetricTypeEnum::YT_PRECISION:
        {
            QVector<PointInfo> point_list = DatabaseManager::queryPoints(alarm_record->substation_id(), static_cast<int>(PointInfo::Type::YT));
            QString yt_point_desc = "";
            for (const PointInfo &point : point_list)
            {
                if (point.point_id == alarm_record->point_address())
                {
                    yt_point_desc = point.point_desc;
                }
            }
            QString yc_point_desc = "";
            auto grab_address = DatabaseManager::queryPointGrab(alarm_record->substation_id(), alarm_record->point_address());
            point_list = DatabaseManager::queryPoints(alarm_record->substation_id(), static_cast<int>(PointInfo::Type::YC));
            for (const PointInfo &point : point_list)
            {
                if (point.point_id == grab_address)
                {
                    yc_point_desc = point.point_desc;
                }
            }

            ruleText = QString("%1秒内设点%2的目标值与关联遥测点%3的值相差")
                           .arg(intervalSeconds)
                           .arg(yt_point_desc)
                           .arg(yc_point_desc);
        }
        break;
        case MetricTypeEnum::YC_SLOPE:
        {
            QVector<PointInfo> point_list = DatabaseManager::queryPoints(alarm_record->substation_id(), static_cast<int>(PointInfo::Type::YC));
            QString yc_point_desc = "";
            for (const PointInfo &point : point_list)
            {
                if (point.point_id == alarm_record->point_address())
                {
                    yc_point_desc = point.point_desc;
                }
            }
            ruleText = QString("%1秒内%2遥测值跳变越限").arg(intervalSeconds).arg(yc_point_desc);
        }
        break;
        default:
            ruleText = "未知告警规则";
            break;
        }

        QTableWidgetItem *ruleItem = new QTableWidgetItem(ruleText);
        ui_->tableWarn->setItem(row, 2, ruleItem);
    }
}

void OverviewView::initRealInstructionList()
{
    ui_->tableInstruct->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); // 某列适应内容
    ui_->tableInstruct->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); // 某列适应内容
    ui_->tableInstruct->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents); // 某列适应内容
    ui_->tableInstruct->horizontalHeader()->setStretchLastSection(true);

    // 请求实时控制指令
    dealer_handler_->sendRequest("select-pointinfos-latest", "50");
}

void OverviewView::updateRealInstructionList()
{
    // 刷新实时控制指令信息
    dealer_handler_->sendRequest("select-pointinfos-latest", "50");
}

void OverviewView::refreshRealInstructionList()
{
    // 清空表格
    ui_->tableInstruct->setRowCount(0);

    // 设置行数
    ui_->tableInstruct->setRowCount(select_frames_result_.size());

    // 遍历数据并填充表格
    for (int i = 0; i < select_frames_result_.size(); ++i)
    {
        const SelectFramesResult &result = select_frames_result_[i];

        // 设置指令时间
        QTableWidgetItem *timeItem = new QTableWidgetItem(result.timestampStr);
        ui_->tableInstruct->setItem(i, 0, timeItem);

        // 设置指令类型
        QTableWidgetItem *typeItem = new QTableWidgetItem(result.tieIdentificationDesc);
        ui_->tableInstruct->setItem(i, 1, typeItem);

        // 设置所属厂站
        QTableWidgetItem *stationItem = new QTableWidgetItem(result.srcName);
        ui_->tableInstruct->setItem(i, 2, stationItem);

        // 设置控制对象
        QTableWidgetItem *objectItem = new QTableWidgetItem(result.pointDesc);
        ui_->tableInstruct->setItem(i, 3, objectItem);
    }
}

void OverviewView::on_timeout()
{
    updateDataOverview();
    updateControlInstructionCycle();
    updateControlInstruction();
    updateTrafficAlarm();
    updateAlarmList();
    updateRealInstructionList();
}

/**
 * @brief 网络应答信号槽
 */
void OverviewView::onNetworkMessageReceived(const QString &method, const QString &body)
{
    // 网络应答
    if (method == "select-all-substation")
    {
        QJsonDocument doc = QJsonDocument::fromJson(body.toUtf8());
        if (!doc.isArray())
        {
            qDebug() << "Invalid JSON data format";
            return;
        }

        QJsonArray array = doc.array();

        // 清空现有的子站信息
        for (auto sub_state_info : state_info_vec_)
        {
            delete sub_state_info;
        }
        state_info_vec_.clear();
        // 处理每个站点信息
        for (const QJsonValue &value : array)
        {
            QJsonObject obj = value.toObject();

            // 创建新的StateInfo对象
            StateInfo *info = new StateInfo();
            info->setId(obj["id"].toInt());
            info->setHost(obj["host"].toString());
            info->setPort(obj["port"].toInt());
            info->setStateName(obj["description"].toString());
            info->setDescription(obj["description"].toString());
            info->setIsRtu(obj["isRtu"].toBool());

            if (!obj["isRtu"].toBool())
            {
                // 更新主站信息
                state_info_->setId(info->id());
                state_info_->setHost(info->host());
                state_info_->setPort(info->port());
                state_info_->setStateName(info->stateName());
                state_info_->setDescription(info->description());
                state_info_->setIsRtu(info->isRtu());
                delete info; // 删除临时对象
            }
            else
            {
                // 添加到子站列表
                state_info_vec_.push_back(info);
            }
        }
        ui_->facNum->setText(QString::number(state_info_vec_.size()));
    }

    if (method == "control-instruction-number")
    {
        control_instruct_num_ = body.toInt();
        ui_->ctrlNum->setText(QString::number(control_instruct_num_));
    }

    if (method == "select-pointinfos-latest")
    {
        QJsonDocument doc = QJsonDocument::fromJson(body.toUtf8());
        if (!doc.isArray())
        {
            qDebug() << "Invalid JSON data format";
            return;
        }
        select_frames_result_.clear();
        QJsonArray array = doc.array();

        for (const QJsonValue &value : array)
        {
            QJsonObject obj = value.toObject();
            SelectFramesResult result;
            result.id = obj["id"].toInt();
            result.tieIdentificationDesc = obj["tieIdentificationDesc"].toString();
            result.srcName = obj["substation"].toObject()["description"].toString();
            result.direction = obj["direction"].toString();
            result.timestamp = obj["timestamp"].toVariant().toLongLong();
            result.timestampStr = QDateTime::fromMSecsSinceEpoch(result.timestamp).toString("yyyy-MM-dd HH:mm:ss.zzz");
            result.pointDesc = obj["pointDesc"].toString();
            select_frames_result_.append(result);
        }
        refreshRealInstructionList();
    }

    if (method == "select-control-instruction-cycle")
    {
        QJsonDocument doc = QJsonDocument::fromJson(body.toUtf8());
        if (!doc.isObject())
        {
            qDebug() << "Invalid JSON data format";
            return;
        }

        QJsonObject obj = doc.object();

        // 初始化categories_
        categories_.clear();
        QJsonArray categoriesArray = obj["categories"].toArray();
        for (const QJsonValue &value : categoriesArray)
        {
            categories_.append(value.toString());
        }

        // 初始化ctrl_list_和set_list_
        ctrl_list_.clear();
        set_list_.clear();
        std::vector<double> ctrl_values;
        std::vector<double> set_values;

        QJsonObject setValues = obj["setValues"].toObject();
        for (const QString &category : categories_)
        {
            QJsonArray values = setValues[category].toArray();
            if (values.size() >= 2)
            {
                ctrl_values.push_back(values[0].toDouble());
                set_values.push_back(values[1].toDouble());
            }
        }

        ctrl_list_.push_back(ctrl_values);
        set_list_.push_back(set_values);
        refreshControlInstructionCycle();
    }

    if (method == "last-30days-instruction-count")
    {
        QJsonDocument doc = QJsonDocument::fromJson(body.toUtf8());
        if (!doc.isArray())
        {
            qDebug() << "Invalid JSON data format";
            return;
        }
        control_instruction_vec_.clear();
        QJsonArray array = doc.array();
        for (const QJsonValue &value : array)
        {
            control_instruction_vec_.push_back(value.toInt());
        }
        refreshControlInstruction();
    }

    if (method == "alarm-number")
    {
        alarm_num_ = body.toInt();
        ui_->warnNum->setText(QString::number(alarm_num_));
    }

    if (method == "get-alarm-record")
    {
        // 解析JSON数据
        QJsonDocument doc = QJsonDocument::fromJson(body.toUtf8());
        if (!doc.isArray())
        {
            qDebug() << "Invalid JSON data format";
            return;
        }
        // 清空告警记录列表
        for (auto alarm_record : alarm_record_vec_)
        {
            delete alarm_record;
        }
        alarm_record_vec_.clear();
        QJsonArray array = doc.array();
        for (const QJsonValue value : array)
        {
            if (!value.isObject())
                continue;

            QJsonObject alarmData = value.toObject();

            int64_t id = alarmData["id"].toInt();
            int status = alarmData["status"].toInt();
            int64_t point_id = alarmData["pointId"].toInt();
            int point_address = alarmData["pointAddress"].toInt();
            double max_threshold = alarmData["maxThreshold"].toDouble();
            int64_t create_at = alarmData["createdAt"].toVariant().toLongLong();
            int64_t update_at = alarmData["updatedAt"].toVariant().toLongLong();
            int64_t substation_id = alarmData["substation"].toObject()["id"].toInt();
            QString substation_desc = alarmData["substation"].toObject()["description"].toString();
            int64_t alarm_rule_id = alarmData["alarmRule"].toObject()["id"].toInt();
            int interval_secs = alarmData["alarmRule"].toObject()["intervalSeconds"].toInt();
            double threshold_value = alarmData["alarmRule"].toObject()["threshold"].toDouble();
            MetricTypeEnum metric_type = static_cast<MetricTypeEnum>(alarmData["alarmRule"].toObject()["metricTypeIndex"].toInt());
            ThresholdUnitEnum threshold_unit = static_cast<ThresholdUnitEnum>(alarmData["alarmRule"].toObject()["thresholdUnitIndex"].toInt());
            AlarmLevelEnum alarm_level = static_cast<AlarmLevelEnum>(alarmData["alarmRule"].toObject()["alarmLevelIndex"].toInt());

            this->appendAlarmRecord(id, status, alarm_rule_id, substation_id, substation_desc, point_id, point_address, max_threshold, create_at, update_at,
                                    interval_secs, threshold_value, metric_type, threshold_unit, alarm_level);
        }
        refreshAlarmList();
    }

    if (method == "last-30days-alarm-count")
    {
        last_30days_alarm_count_.clear();
        QJsonDocument doc = QJsonDocument::fromJson(body.toUtf8());
        if (!doc.isArray())
        {
            qDebug() << "Invalid JSON data format";
            return;
        }
        QJsonArray array = doc.array();
        for (const QJsonValue &value : array)
        {
            last_30days_alarm_count_.push_back(value.toInt());
        }
        refreshTrafficAlarm();
    }
}

void OverviewView::appendAlarmRecord(int64_t id, int status, int64_t alarm_rule_id, int64_t substation_id, QString substation_desc,
                                     int64_t point_id, int point_address, double max_threshold, int64_t create_at, int64_t update_at,
                                     int interval_secs, double threshold_value, MetricTypeEnum metric_type, ThresholdUnitEnum threshold_unit, AlarmLevelEnum alarm_level)
{
    // 创建告警记录
    AlarmRecord *alarm_record = new AlarmRecord(id, status, alarm_rule_id, substation_id, point_id, max_threshold, create_at, update_at);
    alarm_record->set_point_address(point_address);
    // 创建告警规则
    AlarmRule *alarm_rule = new AlarmRule(metric_type, alarm_level, threshold_unit, substation_id);
    alarm_rule->setIntervalSecs(interval_secs);
    alarm_rule->setThresholdValue(threshold_value);
    alarm_record->set_alarm_rule(alarm_rule);

    // 创建变电站信息
    StateInfo *state_info = new StateInfo(substation_id, 0, substation_desc, substation_desc);
    alarm_record->set_state_info(state_info);

    // 创建主站信息
    alarm_record_vec_.prepend(alarm_record);
}
